package com.fzq.web;

import com.fzq.utils.CommonExportExcel;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/excel")
public class ExcelDownloadController {

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadExcel() {
        try {
            // 准备标题数据
            List<Map<String, Object>> title = new ArrayList<>();
            Map<String, Object> title1 = new HashMap<>();
            title1.put("mapping_name", "姓名");
            title1.put("column_name", "name");
            title.add(title1);

            Map<String, Object> title2 = new HashMap<>();
            title2.put("mapping_name", "年龄");
            title2.put("column_name", "age");
            title.add(title2);

            // 准备内容数据
            List<Map<String, Object>> content = new ArrayList<>();
            Map<String, Object> data1 = new HashMap<>();
            data1.put("name", "张三");
            data1.put("age", 25);
            content.add(data1);

            Map<String, Object> data2 = new HashMap<>();
            data2.put("name", "李四");
            data2.put("age", 30);
            content.add(data2);

            // 生成Excel字节数组
            byte[] excelBytes = CommonExportExcel.exportExcelToBytes(title, content);

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "export.xlsx");
            headers.setContentLength(excelBytes.length);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);

        } catch (Exception e) {
            throw new RuntimeException("Excel文件生成失败", e);
        }
    }
}
